package com.ncmmall.mall.controller.securitys;

import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.ncmmall.application.securitys.role.RoleApplication;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.security.role.QRole;
import com.ncmmall.domain.security.role.Role;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author tongchun
 *         角色管理
 */
@RequestMapping(value = "/securitys/roles")
@Controller
public class RoleController {

    private final static Logger logger = LoggerFactory.getLogger(RoleController.class);

    @Value("${web.domain}")
    private String webDomain;

    @Autowired
    private RoleApplication roleApplication;

    @Autowired
    private OperationLogApplication logApplication;

    @Autowired
    private QueryChannelService queryChannelService;

    /**
     * 分页条件筛选
     *
     * @param model
     * @param pageParams
     * @param role
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, Role role) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        String hql = builderSQL("select r from Role r where 1=1 ", params, role);
        QueryPage<Role> page = queryChannelService.findPage(hql, pageRequest.setParams(params), Role.class);
        model.addAttribute("page", page).addAttribute("params", role);

        return "securitys/role/list";
    }

    /**
     * 条件查询
     *
     * @param sql
     * @param params
     * @param role
     * @return
     */
    private String builderSQL(String sql, Map<String, Object> params, Role role) {
        if (!Strings.isNullOrEmpty(role.getShowName())) {
            sql += " and r.showName like :showname";
            params.put("showname", "%" + role.getShowName() + "%");
        }
        return sql;
    }

    /**
     * 添加角色
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    private String create(Model model) {

        model.addAttribute("role", new Role()).addAttribute("_method", "POST");

        return "securitys/role/form";
    }

    /**
     * 添加角色
     *
     * @param role
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> create(HttpServletRequest request, @ModelAttribute Role role) {
        try {

            roleApplication.create(role);

            logApplication.eventOfSystem(Securitys.currentUser(), "添加系统角色" + role.getShowName(), Securitys.getIp(request));

            return ImmutableMap.of("status", true);

        } catch (Exception e) {

            logger.error("[添加角色异常]", e);
            return ImmutableMap.of("status", false, "message", "添加角色异常");
        }
    }

    /**
     * 修改角色
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    private String edit(Model model, @PathVariable("id") long id) {
        Role role = queryChannelService.findOne("select r from Role r where r.id = :id", ImmutableMap.of("id", id), Role.class);

        model.addAttribute("role", role).addAttribute("_method", "PUT");

        return "securitys/role/form";
    }

    /**
     * 修改角色
     *
     * @param role
     * @return
     */
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> edit(HttpServletRequest request, @ModelAttribute Role role) {

        try {
            roleApplication.modify(role);

            logApplication.eventOfSystem(Securitys.currentUser(), "修改系统角色" + role.getShowName(), Securitys.getIp(request));

            return ImmutableMap.of("status", true);
        } catch (Exception e) {

            return ImmutableMap.of("status", false, "message", "修改异常");
        }
    }

    /**
     * 删除角色
     *
     * @param requestWith
     * @param id
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.DELETE)
    @ResponseBody
    private Map<String, Object> remove(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @RequestParam("id") long id) {
        try {

            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be Ajax!");
            }

            Role role = queryChannelService.findOne(QRole.role.id.eq(id), Role.class);

            roleApplication.remove(role);

            logApplication.eventOfSystem(Securitys.currentUser(), "删除系统角色" + role.getShowName(), Securitys.getIp(request));

        } catch (Exception e) {
            logger.error("[角色删除异常]", e);
            return ImmutableMap.of("status", false, "message", "删除角色异常");
        }

        return ImmutableMap.of("status", true);

    }

}
